package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.entity.Page;
import com.tubeonfire.model.admin.PageModel;
import com.tubeonfire.util.IdUniqueHelper;
import com.tubeonfire.util.StringHelper;

@SuppressWarnings("serial")
public class AddPageServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(AddPageServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			Page obj = new Page();
			req.setAttribute("obj", obj);
			req.setAttribute("action", "add");
			req.getRequestDispatcher("/admin/form_page.jsp").forward(req, resp);
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004, "We are sorry for the inconvenience ! Please try again later !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession session = req.getSession();
			String pageTitle = (String) req.getParameter("pageTitle");
			String pageDescription = (String) req
					.getParameter("pageDescription");
			String pageContent = (String) req.getParameter("pageContent");
			Page obj = new Page();
			obj.setTitle(pageTitle);
			obj.setAlias(StringHelper.getAliasByLanguage(pageTitle));
			obj.setDescription(pageDescription);
			obj.setContent(pageContent);
			obj.setStatus(1);
			obj.setId(IdUniqueHelper.getId());
			PageModel.insert(obj);			
			session.setAttribute("success", "Action success !");
			resp.sendRedirect("/admin/page/add");
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			resp.sendError(4004, "We are sorry for the inconvenience ! Please try again later !");
		}
	}
}
